
package gui;

import ij.*;
import ij.process.*;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.AffineTransform;
import javax.media.Buffer;
import javax.media.CaptureDeviceInfo;
import javax.media.CaptureDeviceManager;
import javax.media.Manager;
import javax.media.MediaLocator;
import javax.media.Player;
import javax.media.control.FrameGrabbingControl;
import javax.media.format.VideoFormat;
import javax.media.util.BufferToImage;
import javax.swing.JButton;
import javax.swing.JPanel;

/**
 *
 * @author Ragnar
 */


public class ImagePanel extends JPanel implements Runnable
{
    public static Player player=null;
    public CaptureDeviceInfo di=null;
    public MediaLocator ml=null;
    public JButton capture=null;
    public Buffer buf=null;
    public Image img=null;
    public VideoFormat vf=null;
    public BufferToImage btoi=null;
    public int capturenumber=0;
    public ImagePlus imp;
    
    public ImagePanel()
    {
        String str = "vfw:Microsoft WDM Image Capture (Win32):0";
        di = CaptureDeviceManager.getDevice(str);
        ml = new MediaLocator(str);
        try{
            player = Manager.createRealizedPlayer(ml);
            player.start();
        }
        catch(Exception ex){
            ex.printStackTrace();
        }
                this.setMaximumSize(new Dimension(200, 100));
        this.setMinimumSize(new Dimension(200, 100));
        this.setLayout(null);
        this.setOpaque(true);
        Thread t = new Thread(this);
        t.start();
        
    }
    
    public ImagePlus getIMP()
    {
        return this.imp;
    }
    
    @Override
    public void paintComponent(Graphics g)
    {
        if (this.img != null)
        {
            super.paintComponent(g);
           // double scaleX = this.getWidth() / (double) this.img.getWidth(null);
            //double scaleY = this.getHeight() / (double) this.img.getHeight(null);
            //AffineTransform xform = AffineTransform.getScaleInstance(scaleY, scaleY);
            ((Graphics2D)g).drawImage(this.img, 0,0, this);
            //((Graphics2D)g).drawOval(100, 100, 50, 50);
        }
    }

    @Override
    public void run()
    {
        while(true)
        {
            FrameGrabbingControl fgc = (FrameGrabbingControl) player.getControl("javax.media.control.FrameGrabbingControl");
            buf = fgc.grabFrame();
            btoi= new BufferToImage((VideoFormat)buf.getFormat());
            img = btoi.createImage(buf);
            this.imp = new ImagePlus("",img);
            //this.repaint();
        try {
            Thread.sleep(50);
            this.repaint();
        } catch (InterruptedException ex) {}
        }
    }
    
}
